﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDateTime>
#include <algorithm>
#include <vector>

// 判断红球组合中是否含有三个连续数字
bool hasThreeStraight(const QList<int>& redCombo) {
    QList<int> sorted = redCombo;
    std::sort(sorted.begin(), sorted.end());

    for (int i = 0; i < sorted.size() - 2; ++i) {
        if (sorted[i+1] == sorted[i]+1 && sorted[i+2] == sorted[i]+2)
            return true;
    }
    return false;
}

void generateFilteredCombinations(const QString& filename) {
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件进行写入";
        return;
    }

    QTextStream out(&file);

    const int redTotal = 33;
    const int redPick = 6;
    const int blueTotal = 16;

    // 用于生成红球组合的数组
    std::vector<int> reds(redTotal);
    for (int i = 0; i < redTotal; ++i)
        reds[i] = i + 1;

    std::vector<bool> v(redTotal);
    std::fill(v.begin(), v.begin() + redPick, true);

    qint64 count = 0;
    qint64 redFilteredCount = 0;

    do {
        QList<int> combo;
        for (int i = 0; i < redTotal; ++i) {
            if (v[i]) combo << reds[i];
        }

        // 如果包含三个连续数字，则跳过
        if (hasThreeStraight(combo))
            continue;

        redFilteredCount++;

        // 遍历所有蓝球
        for (int blue = 1; blue <= blueTotal; ++blue) {
            QString line;
            foreach (int r, combo) {
                line += QString("%1 ").arg(r, 2, 10, QChar('0'));
            }
            line += QString("%1").arg(blue, 2, 10, QChar('0'));
            out << line << "\n";

            count++;
            if (count % 1000000 == 0)
                qDebug() << "已生成组合数：" << count;
        }

    } while (std::prev_permutation(v.begin(), v.end()));

    file.close();
    qDebug() << "过滤后的红球组合总数：" << redFilteredCount;
    qDebug() << "最终写入文件的组合总数：" << count;
}

int main(int argc, char *argv[]) {
    Q_UNUSED(argc)
    Q_UNUSED(argv)

    QString filename = "double_color_ball_filtered.txt";
    qDebug() << "开始生成并过滤双色球组合，输出到：" << filename;

    QDateTime start = QDateTime::currentDateTime();

    generateFilteredCombinations(filename);

    qint64 seconds = start.secsTo(QDateTime::currentDateTime());
    qDebug() << "耗时：" << seconds / 3600 << "小时" << (seconds % 3600) / 60 << "分钟" << (seconds % 60) << "秒";

    return 0;
}
